package com.learning.servlet3x.upload;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;

/**
 * ClassName: UploadServlet
 * Description:  HttpServletRequest 对文件上传的支持
 * 1、增强的 HttpServletRequest 方法，直接获取文件，并且操作
 * 2、注解 @MultipartConfig ，定义文件上传 Servlet（表示该 Servlet 希望处理的请求的 MIME 类型是 multipart/form-data）
 * <p>
 * Date: 2014/12/06  9:05 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@WebServlet(name = "uploadServlet", value = {"/uploadServlet"})
@MultipartConfig(fileSizeThreshold = 4096, location = "/data/Learning-Servlet/servlet-3x/upload/",
        maxFileSize = 1024 * 20, maxRequestSize = -1)
public class UploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 根据名称获取文件上传域(multipart/form-data)
        Part part = req.getPart("file");
        //获取上传文件大小
        long size = part.getSize();
        //获得包含原始文件名的字符串
        String info = part.getHeader("content-disposition");
        String fileName = info.substring(info.indexOf("filename=\"") + 10, info.length() - 1);
        part.write("/data/Learning-Servlet/servlet-3x/upload/" + fileName);
    }
}
